import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { Badge } from '@/components/ui/badge';
import { Slider } from '@/components/ui/slider';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useGameStore } from '@/store/game-store';
import { 
  Zap, 
  Star, 
  TrendingUp, 
  Clock, 
  Target,
  Flame,
  Sparkles,
  RotateCcw,
  Play,
  Pause,
  FastForward,
  Award,
  BookOpen,
  Coins
} from 'lucide-react';

export function CultivationPage() {
  const { 
    player, 
    gold,
    gainExperience, 
    breakthrough, 
    skills, 
    learnSkill, 
    upgradeSkill,
    addGold,
    updatePlayer,
    checkQuestProgress
  } = useGameStore();

  // 修炼状态
  const [isCultivating, setIsCultivating] = useState(false);
  const [cultivationProgress, setCultivationProgress] = useState(0);
  const [cultivationTime, setCultivationTime] = useState(0);
  const [cultivationIntensity, setCultivationIntensity] = useState([50]); // 修炼强度 1-100
  const [batchCount, setBatchCount] = useState(1); // 批量修炼次数
  const [autoMode, setAutoMode] = useState(false); // 自动修炼模式
  
  // 修炼效果
  const [cultivationEffects, setCultivationEffects] = useState<Array<{
    id: number;
    type: 'exp' | 'breakthrough' | 'skill';
    value: number;
    text: string;
  }>>([]);

  // 修炼统计
  const [sessionStats, setSessionStats] = useState({
    totalExp: 0,
    totalTime: 0,
    breakthroughs: 0,
    skillUps: 0
  });

  // 计算等级所需经验值
  const calculateMaxExperience = (level: number) => {
    return Math.floor(100 * Math.pow(1.5, level - 1));
  };

  // 计算修炼效率
  const calculateCultivationEfficiency = () => {
    const intensity = cultivationIntensity[0];
    const baseEfficiency = 1 + (intensity - 50) / 100; // 50%强度为基准
    const realmBonus = 1 + player.realm.level * 0.1;
    const manaBonus = player.mana / player.maxMana;
    
    return Math.max(0.1, baseEfficiency * realmBonus * manaBonus);
  };

  // 计算修炼消耗
  const calculateManaCost = () => {
    const intensity = cultivationIntensity[0];
    return Math.floor(intensity / 10); // 强度越高消耗越大
  };

  // 单次修炼
  const performSingleCultivation = () => {
    const manaCost = calculateManaCost();
    
    if (player.mana < manaCost) {
      addCultivationEffect('exp', 0, '灵力不足，修炼失败！');
      return false;
    }

    const efficiency = calculateCultivationEfficiency();
    const baseExp = Math.floor(10 * efficiency);
    const randomBonus = Math.random() * 0.5 + 0.75; // 75%-125%随机
    const finalExp = Math.floor(baseExp * randomBonus);

    // 消耗灵力
    updatePlayer({ mana: Math.max(0, player.mana - manaCost) });

    // 获得经验
    const oldLevel = player.level;
    const maxExp = calculateMaxExperience(player.level);
    
    let newExp = player.experience + finalExp;
    let newLevel = player.level;
    let levelUps = 0;

    // 检查升级 - 修复经验上限问题
    while (newExp >= calculateMaxExperience(newLevel) && newLevel < 100) { // 最高100级
      const currentLevelMaxExp = calculateMaxExperience(newLevel);
      newExp -= currentLevelMaxExp;
      newLevel++;
      levelUps++;
      
      // 如果达到100级，经验值不能超过当前等级上限
      if (newLevel >= 100) {
        newLevel = 100;
        const maxExpFor100 = calculateMaxExperience(100);
        newExp = Math.min(newExp, maxExpFor100 - 1); // 100级经验不能满
        break;
      }
    }

    // 升级奖励
    if (levelUps > 0) {
      const levelBonus = {
        health: 20 * levelUps,
        maxHealth: 20 * levelUps,
        mana: 10 * levelUps,
        maxMana: 10 * levelUps,
        attack: 2 * levelUps,
        defense: 1 * levelUps,
        speed: 1 * levelUps
      };

      updatePlayer({
        level: newLevel,
        experience: newExp,
        maxExperience: calculateMaxExperience(newLevel),
        health: player.health + levelBonus.health,
        maxHealth: player.maxHealth + levelBonus.maxHealth,
        mana: player.mana + levelBonus.mana,
        maxMana: player.maxMana + levelBonus.maxMana,
        attack: player.attack + levelBonus.attack,
        defense: player.defense + levelBonus.defense,
        speed: player.speed + levelBonus.speed
      });
    } else {
      // 没有升级，只更新经验值，确保不超过当前等级上限
      const currentMaxExp = calculateMaxExperience(player.level);
      updatePlayer({
        experience: Math.min(newExp, currentMaxExp - 1) // 确保经验不会达到上限
      });
    }

    if (levelUps > 0) {
      addCultivationEffect('breakthrough', levelUps, `突破${levelUps}级！实力大增！`);
      setSessionStats(prev => ({ ...prev, breakthroughs: prev.breakthroughs + levelUps }));
    } else {
      addCultivationEffect('exp', finalExp, `获得${finalExp}点修为！`);
    }

    // 更新统计
    setSessionStats(prev => ({
      ...prev,
      totalExp: prev.totalExp + finalExp,
      totalTime: prev.totalTime + 1
    }));

    // 检查任务进度
    checkQuestProgress();

    return true;
  };

  // 批量修炼
  const performBatchCultivation = async () => {
    setIsCultivating(true);
    setCultivationProgress(0);

    for (let i = 0; i < batchCount; i++) {
      if (!performSingleCultivation()) {
        break; // 灵力不足时停止
      }

      setCultivationProgress(((i + 1) / batchCount) * 100);
      
      // 添加延迟以显示进度
      await new Promise(resolve => setTimeout(resolve, 200));
    }

    setIsCultivating(false);
    setCultivationProgress(0);
  };

  // 自动修炼
  useEffect(() => {
    let interval: NodeJS.Timeout;
    
    if (autoMode && !isCultivating) {
      interval = setInterval(() => {
        if (player.mana >= calculateManaCost()) {
          performSingleCultivation();
        } else {
          setAutoMode(false);
          addCultivationEffect('exp', 0, '灵力耗尽，自动修炼停止');
        }
      }, 1000);
    }

    return () => {
      if (interval) clearInterval(interval);
    };
  }, [autoMode, isCultivating, player.mana, cultivationIntensity]);

  // 添加修炼效果
  const addCultivationEffect = (type: 'exp' | 'breakthrough' | 'skill', value: number, text: string) => {
    const effect = {
      id: Date.now(),
      type,
      value,
      text
    };

    setCultivationEffects(prev => [...prev, effect]);

    // 3秒后移除效果
    setTimeout(() => {
      setCultivationEffects(prev => prev.filter(e => e.id !== effect.id));
    }, 3000);
  };

  // 境界突破
  const handleBreakthrough = () => {
    if (player.experience >= player.realm.requiredExp) {
      breakthrough();
      addCultivationEffect('breakthrough', 1, `突破至${player.realm.name}！`);
    }
  };

  // 学习功法
  const handleLearnSkill = (skillId: string) => {
    const mockSkill = {
      id: skillId,
      name: '新功法',
      description: '刚学会的功法',
      type: 'attack' as const,
      level: 1,
      maxLevel: 10,
      manaCost: 20,
      damage: 30,
      cooldown: 1,
      requiredRealm: 1
    };
    learnSkill(mockSkill);
    addCultivationEffect('skill', 1, `学会了${mockSkill.name}！`);
  };

  // 恢复灵力
  const restoreMana = () => {
    const cost = Math.floor(player.maxMana * 0.1); // 消耗10%最大灵力值的金币
    if (gold >= cost) {
      updatePlayer({ 
        mana: player.maxMana
      });
      addGold(-cost); // 扣除金币
      addCultivationEffect('exp', 0, '灵力已完全恢复！');
    } else {
      addCultivationEffect('exp', 0, '金币不足，无法恢复灵力！');
    }
  };

  const maxExp = calculateMaxExperience(player.level);
  const expProgress = (player.experience / maxExp) * 100;
  const manaProgress = (player.mana / player.maxMana) * 100;
  const manaCost = calculateManaCost();
  const efficiency = calculateCultivationEfficiency();

  return (
    <div className="min-h-screen bg-gradient-to-b from-slate-900 to-slate-800 p-4 relative overflow-hidden">
      {/* 修炼效果动画 */}
      <AnimatePresence>
        {cultivationEffects.map((effect) => (
          <motion.div
            key={effect.id}
            initial={{ opacity: 0, y: 50, scale: 0.8 }}
            animate={{ opacity: 1, y: -100, scale: 1 }}
            exit={{ opacity: 0, scale: 0.5 }}
            transition={{ duration: 3 }}
            className={`absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 
              text-2xl font-bold pointer-events-none z-50 ${
              effect.type === 'breakthrough' ? 'text-amber-400' :
              effect.type === 'skill' ? 'text-purple-400' :
              'text-green-400'
            }`}
            style={{ 
              left: `${50 + (Math.random() - 0.5) * 20}%`,
              top: `${50 + (Math.random() - 0.5) * 20}%`
            }}
          >
            {effect.type === 'breakthrough' && <Sparkles className="inline h-6 w-6 mr-2" />}
            {effect.type === 'skill' && <BookOpen className="inline h-6 w-6 mr-2" />}
            {effect.type === 'exp' && <TrendingUp className="inline h-6 w-6 mr-2" />}
            {effect.text}
          </motion.div>
        ))}
      </AnimatePresence>

      <div className="max-w-6xl mx-auto space-y-6">
        {/* 角色状态概览 */}
        <Card className="bg-slate-800/50 border-slate-700">
          <CardHeader>
            <CardTitle className="text-2xl text-center text-slate-100 flex items-center justify-center gap-2">
              <Flame className="h-6 w-6 text-amber-400" />
              修炼殿堂
              <Flame className="h-6 w-6 text-amber-400" />
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              {/* 角色信息 */}
              <div className="space-y-4">
                <div className="text-center">
                  <div className="text-4xl mb-2">{player.avatar}</div>
                  <h3 className="text-xl font-semibold text-slate-100">{player.name}</h3>
                  <Badge variant="outline" className="text-amber-400 border-amber-400">
                    {player.realm.name}
                  </Badge>
                </div>

                <div className="space-y-3">
                  <div>
                    <div className="flex justify-between text-sm mb-1">
                      <span className="text-slate-300">等级</span>
                      <span className="text-amber-400">{player.level}</span>
                    </div>
                  </div>

                  <div>
                    <div className="flex justify-between text-sm mb-1">
                      <span className="text-slate-300">修为</span>
                      <span className="text-green-400">{player.experience}/{maxExp}</span>
                    </div>
                    <Progress value={expProgress} className="h-3" />
                  </div>

                  <div>
                    <div className="flex justify-between text-sm mb-1">
                      <span className="text-slate-300">灵力</span>
                      <span className="text-blue-400">{player.mana}/{player.maxMana}</span>
                    </div>
                    <Progress value={manaProgress} className="h-3" />
                  </div>

                  <div>
                    <div className="flex justify-between text-sm mb-1">
                      <span className="text-slate-300">金币</span>
                      <span className="text-yellow-400 flex items-center gap-1">
                        <Coins className="h-3 w-3" />
                        {gold}
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              {/* 修炼控制 */}
              <div className="space-y-4">
                <h4 className="text-lg font-semibold text-slate-100 flex items-center gap-2">
                  <Target className="h-5 w-5 text-green-400" />
                  修炼设置
                </h4>

                <div className="space-y-3">
                  <div>
                    <Label className="text-slate-300">修炼强度: {cultivationIntensity[0]}%</Label>
                    <Slider
                      value={cultivationIntensity}
                      onValueChange={setCultivationIntensity}
                      max={100}
                      min={10}
                      step={10}
                      className="mt-2"
                    />
                    <div className="flex justify-between text-xs text-slate-400 mt-1">
                      <span>省力</span>
                      <span>高效</span>
                    </div>
                  </div>

                  <div>
                    <Label className="text-slate-300">批量修炼次数</Label>
                    <Input
                      type="number"
                      value={batchCount}
                      onChange={(e) => setBatchCount(Math.max(1, Math.min(100, parseInt(e.target.value) || 1)))}
                      min={1}
                      max={100}
                      className="mt-1 bg-slate-700 border-slate-600 text-slate-100"
                    />
                  </div>

                  <div className="grid grid-cols-2 gap-2 text-xs text-slate-400">
                    <div>消耗: {manaCost} 灵力</div>
                    <div>效率: {(efficiency * 100).toFixed(0)}%</div>
                  </div>
                </div>
              </div>

              {/* 本次统计 */}
              <div className="space-y-4">
                <h4 className="text-lg font-semibold text-slate-100 flex items-center gap-2">
                  <Award className="h-5 w-5 text-purple-400" />
                  本次统计
                </h4>

                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-slate-400">获得修为:</span>
                    <span className="text-green-400">{sessionStats.totalExp}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-400">修炼次数:</span>
                    <span className="text-blue-400">{sessionStats.totalTime}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-400">等级突破:</span>
                    <span className="text-amber-400">{sessionStats.breakthroughs}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-400">功法提升:</span>
                    <span className="text-purple-400">{sessionStats.skillUps}</span>
                  </div>
                </div>

                <Button
                  onClick={() => setSessionStats({ totalExp: 0, totalTime: 0, breakthroughs: 0, skillUps: 0 })}
                  variant="outline"
                  size="sm"
                  className="w-full border-slate-600 text-slate-300 hover:bg-slate-700"
                >
                  <RotateCcw className="h-4 w-4 mr-2" />
                  重置统计
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 修炼操作区 */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* 修炼控制面板 */}
          <Card className="bg-slate-800/50 border-slate-700">
            <CardHeader>
              <CardTitle className="text-slate-100 flex items-center gap-2">
                <Zap className="h-5 w-5 text-yellow-400" />
                修炼控制
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* 修炼进度 */}
              {isCultivating && (
                <div>
                  <div className="flex justify-between text-sm mb-2">
                    <span className="text-slate-300">修炼进度</span>
                    <span className="text-green-400">{cultivationProgress.toFixed(0)}%</span>
                  </div>
                  <Progress value={cultivationProgress} className="h-2" />
                </div>
              )}

              {/* 修炼按钮 */}
              <div className="grid grid-cols-2 gap-3">
                <Button
                  onClick={performSingleCultivation}
                  disabled={isCultivating || player.mana < manaCost}
                  className="bg-green-600 hover:bg-green-700 text-white"
                >
                  <Play className="h-4 w-4 mr-2" />
                  单次修炼
                </Button>

                <Button
                  onClick={performBatchCultivation}
                  disabled={isCultivating || player.mana < manaCost}
                  className="bg-blue-600 hover:bg-blue-700 text-white"
                >
                  <FastForward className="h-4 w-4 mr-2" />
                  批量修炼
                </Button>

                <Button
                  onClick={() => setAutoMode(!autoMode)}
                  disabled={isCultivating || player.mana < manaCost}
                  className={`${autoMode ? 'bg-red-600 hover:bg-red-700' : 'bg-purple-600 hover:bg-purple-700'} text-white`}
                >
                  {autoMode ? <Pause className="h-4 w-4 mr-2" /> : <Play className="h-4 w-4 mr-2" />}
                  {autoMode ? '停止自动' : '自动修炼'}
                </Button>

                <Button
                  onClick={restoreMana}
                  disabled={player.mana >= player.maxMana || gold < Math.floor(player.maxMana * 0.1)}
                  className="bg-cyan-600 hover:bg-cyan-700 text-white"
                >
                  <Sparkles className="h-4 w-4 mr-2" />
                  恢复灵力
                </Button>
              </div>

              {/* 提示信息 */}
              <div className="text-xs text-slate-400 space-y-1">
                <p>• 修炼强度影响经验获得和灵力消耗</p>
                <p>• 批量修炼可快速提升，但需要足够灵力</p>
                <p>• 自动修炼会持续进行直到灵力耗尽</p>
                <p>• 恢复灵力需要消耗 {Math.floor(player.maxMana * 0.1)} 金币 (当前: {gold})</p>
              </div>
            </CardContent>
          </Card>

          {/* 境界与功法 */}
          <Card className="bg-slate-800/50 border-slate-700">
            <CardHeader>
              <CardTitle className="text-slate-100 flex items-center gap-2">
                <Star className="h-5 w-5 text-amber-400" />
                境界功法
              </CardTitle>
            </CardHeader>
            <CardContent>
              <Tabs defaultValue="realm" className="w-full">
                <TabsList className="grid w-full grid-cols-2 bg-slate-700">
                  <TabsTrigger value="realm" className="text-slate-300">境界突破</TabsTrigger>
                  <TabsTrigger value="skills" className="text-slate-300">功法修炼</TabsTrigger>
                </TabsList>

                <TabsContent value="realm" className="space-y-4">
                  <div className="text-center space-y-3">
                    <div className="text-2xl">{player.realm.name}</div>
                    <p className="text-sm text-slate-400">{player.realm.description}</p>
                    
                    <div>
                      <div className="flex justify-between text-sm mb-1">
                        <span className="text-slate-300">突破进度</span>
                        <span className="text-amber-400">
                          {player.experience}/{player.realm.requiredExp}
                        </span>
                      </div>
                      <Progress 
                        value={(player.experience / player.realm.requiredExp) * 100} 
                        className="h-3" 
                      />
                    </div>

                    <Button
                      onClick={handleBreakthrough}
                      disabled={player.experience < player.realm.requiredExp}
                      className="w-full bg-amber-600 hover:bg-amber-700 text-white"
                    >
                      <TrendingUp className="h-4 w-4 mr-2" />
                      境界突破
                    </Button>
                  </div>
                </TabsContent>

                <TabsContent value="skills" className="space-y-4">
                  <div className="space-y-3">
                    {skills.length > 0 ? (
                      skills.map((skill) => (
                        <div key={skill.id} className="bg-slate-700/50 rounded p-3">
                          <div className="flex justify-between items-center">
                            <div>
                              <h4 className="font-semibold text-slate-100">{skill.name}</h4>
                              <p className="text-xs text-slate-400">{skill.description}</p>
                            </div>
                            <Badge variant="outline" className="text-purple-400 border-purple-400">
                              {skill.level}/{skill.maxLevel}
                            </Badge>
                          </div>
                        </div>
                      ))
                    ) : (
                      <div className="text-center text-slate-400 py-8">
                        <BookOpen className="h-12 w-12 mx-auto mb-3 opacity-50" />
                        <p>尚未学会任何功法</p>
                        <Button
                          onClick={() => handleLearnSkill('basic_cultivation')}
                          className="mt-3 bg-purple-600 hover:bg-purple-700 text-white"
                          size="sm"
                        >
                          学习基础功法
                        </Button>
                      </div>
                    )}
                  </div>
                </TabsContent>
              </Tabs>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}